﻿using CanDoo.Filter;
using CanDoo.Oil.Core.DTOs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Deployment.Application;
using System.Drawing;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CandooMwrf
{
    public partial class MainForm : Form
    {

#if DEBUG
        private string ServerBaseAddress = System.Configuration.ConfigurationManager.AppSettings["API_URL_TEST"].ToString();
#else
        private string ServerBaseAddress = System.Configuration.ConfigurationManager.AppSettings["API_URL"].ToString();
#endif

        public Int16 Port
        {
            get
            {
                Int16 port = 0;
                int baud = 9600;
                port = (Int16)comboPort.SelectedIndex;
                return port;
            }
        }
        public int Baud
        {
            get
            {
                int baud;
                int nitem = comboBaud.SelectedIndex;
                int[] baudarray = new int[5];
                baudarray[0] = 9600;
                baudarray[1] = 19200;
                baudarray[2] = 38400;
                baudarray[3] = 57600;
                baudarray[4] = 115200;
                baud = baudarray[nitem];
                return baud;
            }
        }

        public List<CustomerApiInfo> Data { get; set; }

        public CardDog CardDog { get; private set; }

        public Action<string> ShowMessage;
        public MainForm()
        {

            Data = new List<CustomerApiInfo>();

            InitializeComponent();

            for (int i = 1; i < 10; i++)
            {
                comboPort.Items.Add("COM" + i);
            }

            string[] ports = SerialPort.GetPortNames();
            if(ports.Length == 1)
            {
                comboPort.SelectedIndex = comboPort.FindString(ports[0]);
            }

            comboBaud.Items.Add("9600");
            //comboBaud.Items.Add("19200");
            //comboBaud.Items.Add("38400");
            //comboBaud.Items.Add("57600");
            //comboBaud.Items.Add("115200");

            //comboPort.SelectedIndex = 2;

            comboBaud.SelectedIndex = 0;
            CardDog = new CardDog();

            ShowMessage = msg => ShowMessageHandler(msg);

            btnDisconnect.Enabled = false;
            btnBeep.Enabled = false;
            btnBurn.Enabled = false;
            btnClear.Enabled = false;
            btnRead.Enabled = false;

            CardDog.ShowMessage = UpdateMessage;
        }

        void UpdateMessage(string message)
        {
            Action action = () =>
            {
                txtResult.Text = message + "\r\n" + txtResult.Text;
                if (txtResult.Text.Length > 1000)
                    txtResult.Text = txtResult.Text.Substring(100);
            };
            this.BeginInvoke(action);
        }

        void ShowCardInfo(Card card)
        {
            Action action = () =>
            {
                if (card == null)
                {
                    ShowMessage("ShowCardInfo 出现一个null card");
                    return;
                }
                lbCardUuid.Text = card.CardSN.ToString();
                txtCardNo.Text = card.CardNo.ToString();
                lblDogVersion.Text = card.DogVersion.ToString();
                lbBirthDate.Text = card.BirthDate.ToShortDateString();
            };
            this.BeginInvoke(action);
        }

        private void ShowMessageHandler(string msg)
        {
            this.Invoke(new Action(() => txtResult.Text = msg + "\r\n" + txtResult.Text));
        }


        private void MainForm_Load(object sender, EventArgs e)
        {
            // 获取当前部署
            ApplicationDeployment appd = ApplicationDeployment.CurrentDeployment;
            var ver = appd.CurrentVersion;// 取得版本号
            this.Text = "塔石售油平台制卡软件" + ver + $"  api地址：{ServerBaseAddress}";

            this.lblDogVersion.Text = CardDog.DogVersion.ToString();

            var rtnMsg = CardDog.Connect(Port, Baud, true);
            if (!string.IsNullOrEmpty(rtnMsg))
                ShowMessage(rtnMsg);
            else
            {
                CardDog.Beep();
                ShowMessage("读写卡器连接成功！");
                ShowMessage("");

                btnConnect.Enabled = false;
                btnDisconnect.Enabled = true;
                btnBeep.Enabled = true;

                btnBurn.Enabled = true;
                btnClear.Enabled = true;
                btnRead.Enabled = true;

                lbHardVer.Text = CardDog.GetHardVer();
            }
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            lbSoftVer.Text = CardDog.GetSoftVer();

            //CardDog.Disconnect();

            var rtnMsg = CardDog.Connect(Port, Baud, true);
            if (!string.IsNullOrEmpty(rtnMsg))
                ShowMessage(rtnMsg);
            else
            {
                CardDog.Beep();
                ShowMessage("读写卡器连接成功！");

                btnConnect.Enabled = false;
                btnDisconnect.Enabled = true;
                btnBeep.Enabled = true;

                btnBurn.Enabled = true;
                btnClear.Enabled = true;
                btnRead.Enabled = true;

                lbHardVer.Text = CardDog.GetHardVer();
            }
        }

        private void btnBeep_Click(object sender, EventArgs e)
        {
            var st = CardDog.Beep();
            lbSoftVer.Text = CardDog.GetSoftVer();
            if (st == 0)
            {
                ShowMessage("读写卡器连接正常！");
                ShowMessage("");
            }
            else
            {
                ShowMessage("");
                //btnDisconnect.Enabled = false;
                //btnConnect.Enabled = true;
                //btnBeep.Enabled = false;
            }



        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            if (CardDog.Disconnect())
            {
                ShowMessage("断开连接成功！");
                btnDisconnect.Enabled = false;
                btnConnect.Enabled = true;
                btnBeep.Enabled = false;
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            common.rf_exit(CardDog.Icdev);
            CardDog.Icdev = 0;
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                var st = -1;
                Card card = null;
                for (int i = 0; i < CardDog.TryCount; i++)
                {
                    st = CardDog.ReadCard(out card);
                    if (st == 0)
                    {
                        ShowCardInfo(card);
                        ShowMessage("读出卡序列号" + card.CardSN);
                        ShowMessage("读出卡号" + card.CardNo);
                        ShowMessage("读出制卡时间" + card.BirthDate);
                        ShowMessage("读出制卡驱动版本" + card.DogVersion);
                        CardDog.Halt();
                        CardDog.Beep();
                        ShowMessage("");


                        return;
                    }
                    else if (st == -5)
                    {
                        ShowMessage("读卡操作失败:" + Result.GetErrorDesc(st));
                        return;
                    }
                    Thread.Sleep(100);
                }
                
                ShowMessage("读卡操作失败:" + Result.GetErrorDesc(st));
                ShowMessage("");
            });
        }

        private void btnBurn_Click(object sender, EventArgs e)
        {
            string cardNo = txtCardNo.Text.Trim().Replace(" ","");
            if (string.IsNullOrEmpty(cardNo) || cardNo.Length > 16)
            {
                ShowMessage("卡号不能为空,也不能大于16位,卡号中间与头尾不能有空格");
                ShowMessage("");
                return;
            }
            
            Task.Factory.StartNew(() =>
            {
                Card card = CardDog.NewCard(cardNo);
                var st = -1;
                for (int i = 0; i < CardDog.TryCount; i++)
                {
                    st = CardDog.BurnCard(card);
                    if (st == 0)
                    {
                        ShowMessage("制卡成功");
                        ShowMessage("");
                        CardDog.Halt();
                        CardDog.Beep();
                        return;
                    }
                    Thread.Sleep(100);
                }
                ShowMessage("制卡操作失败");
                ShowMessage("");
            });
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < CardDog.TryCount; i++)
                {
                    if (CardDog.Clear())
                    {
                        ShowMessage("销卡成功");

                        this.lbCardUuid.Text = string.Empty;

                        CardDog.Halt();
                        CardDog.Beep();
                        ShowMessage("");
                        return;
                    }
                    Thread.Sleep(100);
                }

                ShowMessage("消卡操作失败");
                ShowMessage("");
            });
        }

        private void btnIsBlankCard_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < CardDog.TryCount; i++)
                {
                    if (CardDog.IsBlankCard())
                    {
                        ShowMessage("是空卡");
                        ShowMessage("");
                        CardDog.Beep();
                        return;
                    }
                    Thread.Sleep(100);
                }
                ShowMessage("");
            });
        }

        public void BindData()
        {
            Action action = () =>
            {
                this.bindingSource1.DataSource = null;
                this.bindingSource1.DataSource = this.Data;
            };
            this.BeginInvoke(action);
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                var RowIndex = e.RowIndex;
                this.txtCardNo.Text = this.Data[RowIndex].CardNo;
                this.lbCardUuid.Text = this.Data[RowIndex].PhysicalNo;
            }
            catch (Exception)
            {
            }
        }

        public void LoadData()
        {
            var CardNoStart = toolStripTextBox1.Text;
            var CardNoEnd = toolStripTextBox2.Text;

            if (string.IsNullOrEmpty(CardNoStart) || string.IsNullOrEmpty(CardNoEnd))
            {
                ShowMessage("请先输入读取起止卡号");
                return;
            }
            Action action = async () =>
            {
                Data.Clear();
                CustomerApiService api = new CustomerApiService(ServerBaseAddress);
                var data = await api.DoGet(CardNoStart, CardNoEnd);
                Data.AddRange(data.Data);
                this.bindingSource1.DataSource = null;
                this.bindingSource1.DataSource = this.Data;
            };
            this.BeginInvoke(action);
        }

        private void LoadByCardNo(string cardNo)
        {
            if(string.IsNullOrEmpty(cardNo))
            {
                ShowMessage("请先输入或读取卡号");
                return;
            }
            Action action = async () =>
            {
                CustomerApiService api = new CustomerApiService(ServerBaseAddress);
                var model = await api.DoGet(cardNo);
                if(model != null)
                {
                    var origin = Data.Find(p => p.CardNo == model.CardNo);
                    if (origin == null)
                        Data.Add(model);
                    else
                    {
                        origin.PhysicalNo = origin.PhysicalNo;
                    }
                    this.bindingSource1.DataSource = null;
                    this.bindingSource1.DataSource = this.Data;
                }
            };
            this.BeginInvoke(action);
        }

        public async void SaveAll()
        {
            var api = new CustomerApiService(ServerBaseAddress);
            var or = await api.DoPost(this.Data);
            ShowMessage(or.Message);
        }

        public async void SaveOne()
        {
            if (lbCardUuid.Text == "未知")
            {
                ShowMessage("物理考号为未知，无法保存");
                return;
            }

            var api = new CustomerApiService(ServerBaseAddress);
            var item = Data.Find(p => p.CardNo == this.txtCardNo.Text);
            if (item != null)
            {
                LoadByCardNo(txtCardNo.Text);

                item.PhysicalNo = lbCardUuid.Text;
                item.IsBurn = !string.IsNullOrEmpty(lbCardUuid.Text);

                var rtn = await api.DoPost(new List<CustomerApiInfo> { item });
                ShowMessage(rtn.Message);
            }
        }


        private void tsbSave_Click(object sender, EventArgs e)
        {
            SaveAll();
        }

        private void tsbLoadData_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        private void btnLoadone_Click(object sender, EventArgs e)
        {
            LoadByCardNo(txtCardNo.Text);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveOne();
            //BindData();
        }
    }
}
